package com.atguigu.juc;

import lombok.Getter;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: shenhao
 * @CreatTime: 2024/10/23 21:38
 * @Version: 1.0
 * 3 个销售卖保时米SU7,求三个销售总体销售额
 * 求三个销售的各自独立的个体销售额, 不参加总和计算
 * 必须回收自定义的ThreadLocal变量,可能会影响后续业务逻辑和造成内存泄漏等问题
 */
public class ThreadLocalDemoV1 {
    public static void main(String[] args) throws InterruptedException {
        //线程 操作 资源类
        SU7 su7 = new SU7();
        CountDownLatch latch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            int finalI = i;
            new Thread(() -> {
                int total = 0;
                for (int j = 1; j <= new Random().nextInt(3) + 1; j++) {
                    su7.saleTotal();//本门店销售总和统计,全部加上去
                    su7.salePersonal();
                    total++;
                }
                System.out.println(finalI + "销售卖了" +total+"辆车");
                //获得数据需要使用get方法
                System.out.println(Thread.currentThread().getName()+"号销售独自售卖了"+su7.salePersonal.get()+"辆车");
                latch.countDown();
                //su7.salePersonal.remove();//建议每次使用完threadLocal添加remove, 但是本案例不加 下一个案例
            }, String.valueOf(i)).start();
        }
        latch.await();
        System.out.println(Thread.currentThread().getName()+"销售总额"+su7.getSaleTotal());
    }
}

class SU7 {
    @Getter
    private int saleTotal;//本门店总体销售额

    public synchronized void saleTotal() {
        saleTotal++;
    }
    //ThreadLocal 求三个销售的各自独立的个体销售额, 不参加总和计算
    /*ThreadLocal<Integer> salePersonal = new ThreadLocal<>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };*/
    ThreadLocal<Integer> salePersonal = ThreadLocal.withInitial(() -> 0);
    public void salePersonal() {
        salePersonal.set(salePersonal.get()+1);//累加
    }
}
